package com.leyou.order.interceptor;

import com.leyou.common.utils.CookieUtils;
import com.leyou.entity.UserInfo;
import com.leyou.order.pojo.JwtProperties;
import com.leyou.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserInterceptor implements HandlerInterceptor{

    private JwtProperties jwtProperties;


    public UserInterceptor(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }
    private static final ThreadLocal<UserInfo> threadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取cookie
        String token = CookieUtils.getCookieValue(request, "token");
        try{
            //解析token
            UserInfo userInfo = JwtUtils.getUserInfo(jwtProperties.getPublicKey(), token);
            //传递
            threadLocal.set(userInfo);
            return true;
        }catch (Exception e){
            log.error("解析失败了");
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }

    public static  UserInfo getUser(){
        return threadLocal.get();
    }
}
